package com.vortex.cloud.zhsw.xinyang.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 对实体类中使用的自动填充注解进行编写
 * @author chengzi
 */
@Component
@Primary
public class CreateUpdateMetaObjectHandler implements MetaObjectHandler {

    /**
     * <p>
     * 插入元对象字段填充
     * 包括逻辑删除字段 deleted createTime updateTime
     * </p>
     *
     * @param metaObject 元对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        Boolean deleted = (Boolean) getFieldValByName("deleted", metaObject);
        Integer isDeleted = (Integer) getFieldValByName("isDeleted", metaObject);
        Date createTime = (Date) getFieldValByName("createTime", metaObject);
        if(deleted == null){
            setFieldValByName("deleted",false,metaObject);
        }
        if(isDeleted == null){
            setFieldValByName("isDeleted",0,metaObject);
        }
        if(createTime == null){
            setFieldValByName("createTime",new Date(),metaObject);
        }
        setFieldValByName("updateTime",new Date(),metaObject);
    }

    /**
     * 更新元对象字段填充（用于更新时对公共字段的填充）
     *
     * @param metaObject 元对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        Date updateTime = (Date) getFieldValByName("updateTime", metaObject);
        if(updateTime == null){
            setFieldValByName("updateTime",new Date(),metaObject);
        }
    }


}
